<template>
  <div class="chart-body">
    <div class="chartdom" ref="echartRef"></div>
    <div class="chart-y-bg">
      <div
        class="chart-y-bg-item"
        v-for="(item, index) in bgColor"
        :key="index"
        :style="{ 'background-color': item.color }"
      >
        <div class="name">
          {{ item.name }}
        </div>
        <div class="size">{{ item.size }}</div>
      </div>
    </div>
  </div>
</template>
<script>
import * as echarts from "echarts";
// 需要的数据格式
const obj = {
  name: "中游，零部件", // 名称
  status: 1, // 产业生命周期
  toYear: 70, // 今年
  prevYear: 100, //去年
};

export default {
  name: "",
  props: {
    // 今年数据
    data: {
      type: Array,
      default: () => [],
    },
    // 柱子宽度
    barWidth: {
      type: Number,
      default: 15,
    },
    // 曲线样式
    smooth: {
      type: Boolean,
      default: false,
    },
    symbolSize: {
      type: Number,
      default: 5,
    },
  },
  data() {
    return {
      myChart: null,
      activeYear: [],
      prevYear: [],
      xData: [],
      markArea: [],
      bgColor: [
        {
          name: "高",
          color: "rgba(205, 254, 215, 1)",
          size:80
        },
        {
          name: "较高",
          color: "rgba(222, 242, 246, 1)",
          size:60
        },
        {
          name: "中等",
          color: "rgba(223, 235, 249, 1)",
          size:40
        },
        {
          name: "较低",

          color: "rgba(255, 241, 232, 1)",
          size:20
        },
        {
          name: "低",

          color: "rgba(253, 218, 221, 1)",
          size:0
        },
      ],
      labelStyle: {
        color: "#333",
        fontSize: 14,
        fontFamily: "Microsoft YaHei",
        fontWeight: 400,
      },
    };
  },
  watch: {
    data(newVal) {
      this.init();
    },
  },
  computed: {},
  mounted() {
    this.init();
  },
  unmounted() {
    window.removeEventListener("resize", this.getResize);
  },
  methods: {
    // 初始化，数据变动皆调用
    init() {
      this.initData();
      if (!this.myChart) {
        this.initChat();
      }
      this.initOption();
    },
    initChat() {
      this.myChart = echarts.init(this.$refs.echartRef);
      window.addEventListener("resize", this.getResize);
    },
    // 根据传入的数据格式，修改组件需要的格式
    initData() {
      const obj = {
        name: "中游，零部件", // 名称
        status: 1, // 产业生命周期
        toYear: 70, // 今年
        prevYear: 100, //去年
      };
      console.log(this.data);
      this.activeYear = [];
      this.prevYear = [];
      this.markArea = [];
      this.xData = [];
      const sortData = this.data.sort((a, b) => a.status - b.status);
      // 循环加入数组， 并且生成 mark的值（背景位置）
      this.markArea = sortData.reduce((result, item, index) => {
        const toYear = item.toYear ? Math.floor(item.toYear * 100) / 100 : 0;
        const prevYear = item.prevYear
          ? Math.floor(item.prevYear * 100) / 100
          : 0;
        this.activeYear.push(toYear);
        this.prevYear.push(prevYear);
        this.xData.push(item.name);
        if (!result[item.status]) {
          result[item.status] = [item.name];
        } else {
          result[item.status][1] = item.name;
        }
        return result;
      }, {});

      console.log(this.markArea);
    },
    getResize() {
      this.myChart.resize();
      console.log("屏幕宽度变化");
    },
    // 根据最大最小值，获取适合摆放文字的位置
    getMaxMinName(num1, num2) {
      const maxSize = Math.max(num1, num2);
      const minSize = Math.min(num1, num2);
      const gap = maxSize % 100;
      const tops = [maxSize, "-"];
      const bottoms = ["-", minSize];
      // 如果下面很宽敞，则放置在下面
      if (minSize > 50) {
        return bottoms;
      } else if (maxSize < 50) {
        return tops;
      } else if (gap > minSize) {
        // 如果上面空隙大于下面空隙，则放置在上面
        return tops;
      } else {
        return bottoms;
      }
    },
    // 根据数据生成柱子
    getBarData(active, prev) {
      const length = Math.max(active.length, prev.length);
      const redSize = []; // 红色柱子
      const blueBar = []; // 蓝色柱子
      const minBar = []; // 透明柱子
      const maxName = [];
      const minName = [];

      Array(length)
        .fill(0)
        .forEach((_, index) => {
          const start = active[index];
          const end = prev[index];
          const differ = start - end;

          minBar.push(Math.min(start, end));
          // - 用于 hover的时候隐藏对于的值
          redSize.push(differ < 0 ? Math.abs(differ).toFixed(2) : "-");
          blueBar.push(differ >= 0 ? Math.abs(differ).toFixed(2) : "-");
          const [max, min] = this.getMaxMinName(start, end);
          maxName.push(max);
          minName.push(min);
        });
      return [minBar, redSize, blueBar, maxName, minName];
    },
    // 获取echarts 数据并且写入
    initOption() {
      this.myChart.clear();
      // 图表配置项
      const option = this.getOption();
      // 渲染配置
      this.myChart.setOption(option);
      const zoomSize = 2;

      this.myChart.on("click", (params) => {
        const start =
          this.activeYear[Math.max(params.dataIndex - zoomSize / 2, 0)];
        console.log(start);
        this.myChart.dispatchAction({
          type: "dataZoom",
          startValue: start,
          endValue:
            this.activeYear[
              Math.min(
                params.dataIndex + zoomSize / 2,
                this.activeYear.length - 1
              )
            ],
        });
      });
    },

    getData() {
      let arrData = [];
      if (this.activeYear && this.activeYear.length > 0 && false) {
        arrData.push({
          name: "本年",
          type: "line",
          symbolSize: this.symbolSize,
          symbol: "circle",
          data: this.activeYear,

          smooth: this.smooth,
          itemStyle: {
            width: 10,
            shadowColor: "rgba(0, 0, 0, 0.2)",
            shadowBlur: 10,
            shadowOffsetX: 20,
            shadowOffsetY: 10,
            color: "rgba(0, 78, 162, 1)",
          },
          label: {
            show: false,
            precision: 1,
            position: "bottom",
            fontSize: 12,
            color: "#000",
            valueAnimation: true,
            formatter: function (params) {
              console.log(params);
              const length = params.name.toString().length;
              const name =
                length > 10 ? params.name.slice(0, 10) + "." : params.name;
              return name.split("").join("\n"); //垂直显示
            },
          },
        });
      }
      // 去年的线
      if (this.prevYear && this.prevYear.length > 0 && false) {
        arrData.push({
          name: "上年",
          type: "line",
        
          smooth: this.smooth,
          symbolSize: this.symbolSize,
          symbol: "circle",
          data: this.prevYear,
          itemStyle: {
            color: "rgba(141, 214, 207, 1)",
          },
        });
      }
      // 只有两年才存在，才需要柱状图
      if (
        this.prevYear &&
        this.prevYear.length > 0 &&
        this.activeYear &&
        this.activeYear.length > 0
      ) {
        const [minBar, redSize, blueBar, maxName, minName] = this.getBarData(
          this.activeYear,
          this.prevYear
        );

        const barArr = [
          {
            name: "差值",
            type: "bar",
            data: minBar,
            stack: "Total",
            silent: true,
            tooltip: {
              show: false,
            },

            itemStyle: {
              borderColor: "transparent",
              color: "transparent",
              zIndex: 10,
            },
            emphasis: {
              itemStyle: {
                borderColor: "transparent",
                color: "transparent",
                zIndex: 10,
              },
            },
          },
          {
            name: "较去年下降",
            type: "bar",
            stack: "Total",
            data: redSize,
            barWidth: this.barWidth,
            legend: {
              icon: "circle",
            },
            itemStyle: {
              borderColor: "transparent",
              color: "rgba(254, 94, 86, 1)",
              zIndex: 10,
            },
            z: 100,
          },
          {
            name: "较去年上升",
            type: "bar",
            stack: "Total",
            data: blueBar,
            legend: {
              show: false,
              icon: "circle",
            },
            barWidth: this.barWidth,
            itemStyle: {
              borderColor: "transparent",
              color: "rgba(2, 190, 151, 1)",
              zIndex: 10,
            },
            z: 100,
          },
          {
            name: "显示在上面区域",
            type: "line",
            tooltip: {
              show: false,
            },
            label: {
              show: true,
              position: "top",
              offset: [0, -20],
              ...this.labelStyle,
              formatter: function (params) {
                const length = params.name.toString().length;
                const name =
                  length > 10 ? params.name.slice(0, 10) + "." : params.name;
                return name.split("").join("\n"); //垂直显示
              },
            },
            silent: true,
            itemStyle: {
              borderColor: "transparent",
              color: "transparent",
            },

            emphasis: {
              itemStyle: {
                borderColor: "transparent",
                color: "transparent",
              },
            },
            data: maxName,
          },
          {
            name: "显示在下面区域",
            type: "line",
            tooltip: {
              show: false,
            },
            label: {
              show: true,
              position: "bottom",
              offset: [0, 10],

              ...this.labelStyle,
              formatter: function (params) {
                const length = params.name.toString().length;
                const name =
                  length > 10 ? params.name.slice(0, 10) + "." : params.name;
                return name.split("").join("\n"); //垂直显示
              },
            },
            silent: true,
            itemStyle: {
              borderColor: "transparent",
              color: "transparent",
            },

            emphasis: {
              itemStyle: {
                borderColor: "transparent",
                color: "transparent",
              },
            },
            data: minName,
          },
        ];
        arrData.push(...barArr);
      }
      return arrData;
    },
    getOption() {
      return {
        dataZoom: [
          {
            type: "inside", // "slider",
            xAxisIndex: 0,
          },
        ],
        title: {
          text: "产业景气度",
          show: true,
          left: 30,
          top: 20,
          textStyle: {
            color: '#000',
            fontSize:16,
          }
        },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          top: "20",
          right: "200",
          textStyle:{
              fontSize:14
          },
          itemHeight:12,
          data: [
            { name: "本年", }, // 使用矩形图标
            { name: "上年",  }, // 使用线条图标 icon: "rect"
            { name: "较去年上升", icon: "circle" },
            { name: "较去年下降", icon: "circle" },
          ],
    
        },
        grid: {
          left: 120,
          right: "4%",
          bottom: "3%",
          top: 76,
          containLabel: true,
        },
        toolbox: {
          show: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: true,
          // prettier-ignore
          data: this.xData,

          axisTick: {
            show: false,
          },
          axisLine: {
            show: false, // 隐藏轴线
          },
          axisLabel: {
            show: false, // 隐藏轴标签
          },
        },
        yAxis: {
          type: "value",

          min: 0, // 设置y轴最小值
          max: 100, // 设置y轴最大值
          splitNumber: 0, // 设置分割区域数量
          show: false,
          axisLabel: {
            show: false, // 隐藏轴标签
            margin: 40, // 控制轴标签距离轴线的距离
            offset: [10, -30],
            align: "center",
            formatter: function (value) {
              switch (value) {
                case 0:
                  return "低";
                case 20:
                  return "较低";
                case 40:
                  return "中";
                case 60:
                  return "较高";
                case 80:
                  return "高";
                default:
                  return "";
              }
            },
          },
          splitArea: {
            interval: "auto",
            show: false,
            areaStyle: {
              color: [
                "rgba(254, 204, 203, 1)",
                "rgba(254, 231, 207, 1)",
                "rgba(255, 251, 205, 1)",
                "rgba(231, 255, 204, 1)",
                "rgba(205, 254, 215, 1)",
              ],
              shadowColor: "rgba(256, 256, 256, 1)",
              shadowBlur: 30,
            },
          },

          axisTick: {
            show: false,
          },
          axisLine: {
            show: false, // 隐藏轴线
          },
          axisPointer: {
            snap: false,
          },
        },

        series: this.getData(),
      };
    },
  },
};
</script>
<style lang="scss" scoped>
.chart-body {
  width: 100%;
  height: 100%;
  position: relative;

  box-sizing: border-box;
}
.chartdom {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 9;
}
$jj: 30px;
.chart-y-bg {
  position: absolute;
  bottom: $jj;
  left: $jj;
  right: $jj;
  top: 76px;
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
  flex-direction: column;
  &-item {
    $border: 10px;
    flex: 1;
    width: 100%;
    position: relative;
    border-radius: $border;
    overflow: hidden;
    .name {
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 50px;
      writing-mode: vertical-lr;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
      color: #fff;
      line-height: 40px;
      border-radius: $border;
    }
    .size{
        position: absolute;
        left: 60px;
        bottom: 5px;
        color: #666;
        color: transparent;
    }
  }
}

$colors: #90dc83, #59c8ee, #3f7cff, #fbb680, #f78a8f;
@for $i from 1 through length($colors) {
  $color: nth($colors, $i);
  .chart-y-bg .chart-y-bg-item:nth-child(#{$i}) .name {
    background-image: linear-gradient(
      to bottom,
      $color,
      rgba($color: $color, $alpha: 0.3)
    );
  }
}
</style>
